package com.hdcircles.autoform.model.http;

import android.util.Log;

import com.hdcircles.autoform.app.App;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.util.LogUtil;
import com.hdcircles.autoform.util.RxUtil;
import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.persistent.FileRecorder;
import com.qiniu.android.utils.UrlSafeBase64;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import top.zibin.luban.Luban;

/**
 * Created by hdcircles on 2016/11/26.
 */

public class ImageHelper {

    private  UploadManager uploadManager;

    private  String mToken="";
    private  String imgPath;

    private uploadListener listener;

    @Inject
    public ImageHelper(){
        initUploadManager();
    }

    public  void uploadPicture(String path,String token) {
        mToken=token;
        LogUtil.d(mToken);
        final String[] imageUrl = {""};
        Luban.get(App.getInstance())
                .load(new File(path))
                .launch()
                .asObservable()
                .compose(RxUtil.<File>rxScheduleHelper())
                .doOnError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                })
                .onErrorResumeNext(new Func1<Throwable, Observable<? extends File>>() {
                    @Override
                    public Observable<? extends File> call(Throwable throwable) {
                        return Observable.empty();
                    }
                })
                .subscribe(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        upload2QiNiu(file);
                    }
                });

    }

    public void setUploadListener(uploadListener listener) {
        this.listener = listener;
    }

    public interface uploadListener{
        void success(String url);
    }


    private  void initUploadManager(){
        //断点上传
        String dirPath = "/storage/emulated/0/Download";
        Recorder recorder = null;
        try {
            File f = File.createTempFile("qiniu_xxxx", ".tmp");
            Log.d("qiniu", f.getAbsolutePath().toString());
            dirPath = f.getParent();
            recorder = new FileRecorder(dirPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        final String dirPath1 = dirPath;
        //默认使用 key 的url_safe_base64编码字符串作为断点记录文件的文件名。
        //避免记录文件冲突（特别是key指定为null时），也可自定义文件名(下方为默认实现)：
        KeyGenerator keyGen = new KeyGenerator() {
            public String gen(String key, File file) {
                // 不必使用url_safe_base64转换，uploadManager内部会处理
                // 该返回值可替换为基于key、文件内容、上下文的其它信息生成的文件名
                String path = key + "_._" + new StringBuffer(file.getAbsolutePath()).reverse();
                Log.d("qiniu", path);
                File f = new File(dirPath1, UrlSafeBase64.encodeToString(path));
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                    String tempString = null;
                    int line = 1;
                    try {
                        while ((tempString = reader.readLine()) != null) {
//							System.out.println("line " + line + ": " + tempString);
                            Log.d("qiniu", "line " + line + ": " + tempString);
                            line++;
                        }

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        try {
                            reader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return path;
            }
        };

        Configuration config = new Configuration.Builder()
                // recorder 分片上传时，已上传片记录器
                // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .recorder(recorder, keyGen)
                .build();
        // 实例化一个上传的实例
        uploadManager = new UploadManager(config);
    }
    private  void upload2QiNiu(File file){
        HashMap<String,String> map=new HashMap<>();
        map.put("x:phone", "12345678");
        LogUtil.d("upload");
        final boolean isCancelled=false;
        uploadManager.put(file.getPath(), null, mToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Logger.d(key + ",\r\n " + info
                                + ",\r\n " + response);
                        if (info.isOK()){
                            try {
                                String str=response.getString("key");
                                Logger.d("success");
                                imgPath= Constants.IMAGE_URL+str;
                                listener.success(imgPath);
                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                        }
                    }
                },new UploadOptions(map, null, false, new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        LogUtil.d(key+":"+percent);
                    }
                }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return isCancelled;
                    }
                }));
    }
}
